import React, { useState, useEffect } from 'react'
import { Modal, message, Button, Table } from 'antd'
import { useNavigate, Outlet } from 'react-router-dom'
import axios from 'axios'
import { servicePath } from '@src/api/axios'
import { rTime } from '@src/utils/rTime'
import './index.module.css'
import 'antd/dist/antd.css'

const { confirm } = Modal
const { Column } = Table

export const ArticleList = () => {

  const navigate = useNavigate()
  // 存放文章列表
  const [articleList, setArticleList] = useState([])

  // 向中台请求文章列表数据的方法
  const getArticleList = () => {
    axios({
      method: 'get',
      url: servicePath.getArticleList,
      withCredentials: true,
      header: { 'Access-Control-Allow-Origin': '*' }
    }).then(res => res.data.articleList.map(item => {
      // 时间格式是国际格式，转化为北京时间
      item.addTime = rTime(item.addTime)
      return item
    }))
      .then(res => {
        console.log(res)
        setArticleList(res)
      })
  }

  // 编辑文章点击事件
  const uodataArticleClick = id => {
    navigate(`/reviseArticle`, { state: { id: id }, replace: true })
  }

  //删除文章点击事件
  const delArticleClick = id => {
    confirm({
      title: '确定要删除这篇博客文章吗?',
      content: '如果你点击OK按钮，文章将会永远被删除，无法恢复。',
      onOk() {
        axios(servicePath.deleteArticle + id, { withCredentials: true })
          .then(() => {
            message.success('文章删除成功')
            getArticleList()
          })
      },
      onCancel() {
        message.success('取消删除操作')
      },
    })

  }

  useEffect(() => {
    // 请求文章列表数据
    getArticleList()
  }, [])

  return (
    <>
      <Table
        key="1"
        bordered
        dataSource={articleList}
      >
        <Column
          key="title"
          title="文章标题"
          align='left'
          dataIndex="title"
        />
        <Column
          key="typeName"
          title="文章类别"
          align='left'
          dataIndex="typeName"
        />
        <Column
          key="addTime"
          title="发布时间"
          align='left'
          dataIndex="addTime"
        />
        <Column
          key="view_count"
          title="浏览次数"
          align='left'
          dataIndex="view_count"
        />
        <Column
          key="id"
          title="操作"
          align='center'
          render={(text, record, index) => (
            <>
              {/* <Button type="primary" onClick={() => addArticleClick(record.id)}>编辑</Button> */}
              <Button
                type="primary"
                onClick={() => uodataArticleClick(record.id)}>
                <span>编辑</span>
              </Button>
              <Button type="danger" onClick={() => delArticleClick(record.id)}>删除</Button>
            </>
          )}
        />
      </Table>
      <Outlet />
    </>
  )
}